package com.xtsoft.platform.task.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;


import com.xtsoft.platform.globe.enums.AgentStr;

import com.xtsoft.platform.task.domain.CommonTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;




@Service
public class TaskSchedulersService {
//	@Autowired
//	private ThreadPoolTaskScheduler threadPoolTaskScheduler;

	private final static Logger logger = LoggerFactory.getLogger(TaskSchedulersService.class);

	// 任务列表
	private Map<String, ScheduledFuture<?>> mapFuture = new HashMap();

	/**
	 * 
	 * 
	 * 
	 * 
	 * @Title: startTask
	 * @Description: 启动一个监控任务
//	 * @param CommonTask
	 *            任务对象
	 * @param obj
	 *            BusDevice或BusService对象
	 * @return String
	 * @throws @author
	 *             defencez
	 * @date 2018年8月14日
	 */
	public String startTask(CommonTask obj) {
		String result = AgentStr.Rep_StartDeviceSuccess.getDes();
		if(mapFuture.containsKey(obj.getTaskId())) {
			stopTask(obj);
		}
		// 新建任务，暂时屏蔽
//		ScheduledFuture<?> future = threadPoolTaskScheduler.schedule(obj,new CronTrigger(obj.getCron()));
//		if(null == future) {
//			result = AgentStr.Rep_StartDeviceFault.getDes();
//			logger.debug(obj.getTaskName() + " 启动"  + result);
//		}else {
//			mapFuture.put(obj.getTaskId(), future);
//			logger.debug(obj.getTaskName() + " 启动" + result);
//		}
		return result;
	}

	/**
	 * 
	 * @Title: stopTask
	 * @Description: 停止任务
//	 * @param taskId
	 *            void
	 * @throws @author
	 *             defencez
	 * @date 2018年7月31日
	 */
	public String stopTask(CommonTask obj) {
		String result = AgentStr.Rep_StopDerviceSuccess.getDes();
		if (this.mapFuture.containsKey(obj.getTaskId())) {
			ScheduledFuture<?> future = this.mapFuture.get(obj.getTaskId());
			if (future != null) {
				future.cancel(true);
				this.mapFuture.remove(obj.getTaskId());
				
			} else {
				this.mapFuture.remove(obj.getTaskId());
			}
		}
		logger.debug(obj.getTaskName() + "  停止" + result);		
		return result;
	}

	/**
	 * 
	 * @Title: isExistTask  
	 * @Description: 任务是否存在  
	 * @param taskId
	 * @return boolean   
	 * @throws  
	 * @author defencez  
	 * @date 2018年10月25日
	 */
	public boolean isTaskExist(String taskId) {
		return this.mapFuture.containsKey(taskId);
	}	
}
